package com.ruoyi.web.es.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.web.es.beans.Bdindex;
import com.ruoyi.web.es.beans.ElasticSearchConfiguration;
import com.ruoyi.web.es.beans.User;
import com.ruoyi.web.es.impl.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Anonymous
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Bdindex bdindex;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /***
     * 往es中添加值 user
     */
    @PostMapping("/userAdd")
    public void userAdd(){
        //进行索引预处理
        bdindex.preindex();

        List<User> userList = new ArrayList<>(10000);
        for (int i = 0; i < 10000; i++) {
            User user = new User();

            user.setUsername("zhangsan" + i);
            user.setGender("男");
            user.setAge(i + i);
            user.setAddress("河北省" + i);
            userList.add(user);
        }
        userMapper.saveAll(userList);
    }

    /***
     * 根据索引id删除值
     * @param map
     * @return
     */
    @PostMapping("/userDeleIndex")
    public boolean userDeleIndex(@RequestBody Map<String,String> map){
        String index = map.get("index");
        //传递索引名称
        ElasticSearchConfiguration.apiCallIndexNamePrefix = index;

        IndexOperations indexOperations = restTemplate.indexOps(User.class);

        return indexOperations.delete();
    }

    @PostMapping("/userTotal")
    public long userTotal(){

        return userMapper.count();
    }

}
